package com.codebo.yunpicturebackend.controller;

import com.codebo.yunpicturebackend.annotation.AuthCheck;
import com.codebo.yunpicturebackend.common.BaseResponse;
import com.codebo.yunpicturebackend.common.ErrorCode;
import com.codebo.yunpicturebackend.common.ResultUtils;
import com.codebo.yunpicturebackend.exception.BusinessException;
import com.codebo.yunpicturebackend.exception.ThrowUtils;
import com.codebo.yunpicturebackend.manager.CosManager;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController
{
    @Resource
    private CosManager cosManager;

    @PostMapping("/test/upload")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<String> testUpload(@RequestPart MultipartFile multipartFile)
    {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "上传文件为空");
        String originalFilename = multipartFile.getOriginalFilename();
        String filePath = String.format("/test/%s", originalFilename);
        File file = null;

        try
        {
            file = File.createTempFile(filePath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filePath, file);
            return ResultUtils.success(filePath);
        } catch (Exception e)
        {
            log.error("上传失败，文件路径为：{}", filePath);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally
        {
            if (file != null)
            {
                boolean delete = file.delete();
                if (!delete)
                {
                    log.error("删除临时文件失败，文件路径为：{}", file.getAbsolutePath());
                }
            }
        }
    }

    @PostMapping("/test/download")
    @AuthCheck(mustRole = "admin")
    public void testDownload(String filePath, HttpServletResponse httpServletResponse)
    {
        COSObject cosObject = cosManager.getObject(filePath);
        COSObjectInputStream cosObjectInputStream = cosObject.getObjectContent();
        byte[] bytes = null;
        try
        {
            bytes = IOUtils.toByteArray(cosObjectInputStream);
            //设置请求头，触发自动下载
            httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + filePath);
            httpServletResponse.setContentType("application/octet-stream");
            //写入响应
            httpServletResponse.getOutputStream().write(bytes);
            httpServletResponse.getOutputStream().flush();
        } catch (IOException e)
        {
            log.error("文件下载失败，文件路径为：{}", filePath);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件下载失败");
        } finally
        {
            if (cosObjectInputStream != null)
            {
                try
                {
                    cosObjectInputStream.close();
                } catch (IOException e)
                {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件下载流关闭失败");
                }
            }
        }

    }
}
